import logging
from google.appengine.ext import db

relationtypes = ['owns', 'secowns']#valid relation types.  For the sake of consistency
                                    #let's keep only active verbs in this list
class Av(db.Model):
    id = db.StringProperty()
    name = db.StringProperty()

class Relation(db.Model):
    subj_id = db.StringProperty()
    type = db.StringProperty()
    obj_id = db.StringProperty()
    
def key2name(key):
    """given an av uuid, returns av name.  Returns None if av not found"""
    av = Av.gql("WHERE id = :1", key).get()
    if av:
        return av.name
    else:
        return None

def update_av(id, name):
    """update's av's name if key found, else creates entity.  only use request header data.  POST and PUT data are not trustworthy."""
    query = Av.gql("WHERE id = :1", id)
    if query.count() == 0:#doesn't exist. save
        av = Av(id = id, name = name)    
        av.put()    
    elif query.count() == 1:#already exists.  just update the name
        av = query.get()
        av.name = name
        av.put()
    else:#there's more than one record.  delete them all and just save one
        for record in query:
            record.delete()
        av = Av(id = id, name = name)    
        av.put()        
        
    
def getby_subj_type(subj, type):
    """returns all relation entities with given subj, type"""
    return Relation.gql("WHERE subj_id = :1 AND type = :2", subj, type)
    
def getby_obj_type(obj, type):
    """returns all relation entities with given obj, type"""
    return Relation.gql("WHERE obj_id = :1 AND type = :2", obj, type)    
    
def getby_subj_obj(subj, obj):
    """returns all relation entities with given subj_id and obj_id"""
    return Relation.gql("WHERE subj_id = :1 AND obj_id = :2", subj, obj)    
    
def create_unique(subj, type, obj):
    """creates relation with given subj_id, type, and obj_id, if not already present"""
    query = Relation.gql("WHERE subj_id =  :1 AND type = :2 and obj_id = :3", subj, type, obj)
    if query.count() == 0:
        record = Relation(subj_id = subj, type = type, obj_id = obj)
        record.put()
    
def delete(subj, type, obj):
    """deletes any and all entities with given subj_id, type, and obj_id"""
    query = Relation.gql("WHERE subj_id =  :1 AND type = :2 and obj_id = :3", subj, type, obj)
    for record in query:
        record.delete()
        
def del_by_obj(obj):
    """deletes any and all entities with given obj_id"""
    query = Relation.gql("WHERE obj_id = :1", obj)
    for record in query:
        record.delete()   
        
def del_by_obj_type(obj, type): 
    """deletes any and all entities with given obj_id and type"""  
    query = Relation.gql("WHERE obj_id = :1 AND type = :2", obj, type)
    for record in query:
        record.delete()  
    